@echo off
:: Check if the script is running as administrator
net session >nul 2>&1
if %errorLevel% == 0 (
    echo Running as administrator...
) else (
    echo Please run this script as administrator!
    pause
    exit /b
)

:: Fetch the download URL for the latest Git version
echo Fetching the latest Git version...
for /f "delims=" %%i in ('powershell -Command "(Invoke-WebRequest -Uri 'https://api.github.com/repos/git-for-windows/git/releases/latest' -UseBasicParsing).Content | ConvertFrom-Json | Select-Object -ExpandProperty assets | Where-Object { $_.name -like '*-64-bit.exe' } | Select-Object -ExpandProperty browser_download_url"') do (
    set GIT_URL=%%i
)

:: Set the path to save the installer
set INSTALLER_PATH=%TEMP%\Git-Installer.exe

:: Download the Git installer
echo Downloading Git installer...
powershell -Command "Invoke-WebRequest -Uri '%GIT_URL%' -OutFile '%INSTALLER_PATH%'"

:: Install Git silently
echo Installing Git...
start /wait "" "%INSTALLER_PATH%" /VERYSILENT /NORESTART

:: Delete the installer after installation
echo Deleting the installer...
del "%INSTALLER_PATH%"

:: Add Git to the system environment variables
echo Adding Git to the system environment variables...
setx PATH "%PATH%;C:\Program Files\Git\cmd" /M

echo Git installation completed and added to the system environment variables.
pause